import 'dart:convert';
import 'dart:core';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_niandaxue/model/base_model.dart';
import 'package:flutter_niandaxue/service/http_service.dart';
import 'package:flutter_niandaxue/utils/string_utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class QuestionShowView extends StatefulWidget {
  // 创建内置属性接受外部数据,我也不知道为什么要加final关键词，按照课程还是加上
  Question question;
  bool answerFlag;
  String countMsg;
  int sourceType;
  // 初始化函数
  QuestionShowView({Key key,@required this.question,@required this.answerFlag, @required this.countMsg, @required this.sourceType});
  @override
  State<StatefulWidget> createState() => new QuestionShowViewState(key: key, question: this.question,
      answerFlag: this.answerFlag, countMsg: this.countMsg, sourceType: this.sourceType);
}

class QuestionShowViewState extends State<QuestionShowView> with AutomaticKeepAliveClientMixin {
  // 创建内置属性接受外部数据,我也不知道为什么要加final关键词，按照课程还是加上
  Question question;
  bool answerFlag;
  String countMsg;
  int sourceType;
  // 初始化函数
  QuestionShowViewState({Key key, this.question, this.answerFlag, this.countMsg, this.sourceType});

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      //这里从前一视图传递了参数进来，没有有任何的修改
      child: QuestionShowColumnPage(question: this.question, answerFlag: this.answerFlag,
          countMsg:this.countMsg, sourceType: this.sourceType),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}


class QuestionShowColumnPage extends StatefulWidget {
  Question question;
  bool answerFlag;
  String countMsg;
  final int sourceType;
  QuestionShowColumnPage({Key key,@required this.question, @required this.answerFlag,
    @required this.countMsg, @required this.sourceType}):super(key:key);
  @override
  State<StatefulWidget> createState() => new QuestionShowColumnState(question: this.question,
      answerFlag: this.answerFlag, countMsg:this.countMsg, sourceType: this.sourceType);
}

class QuestionShowColumnState extends State<QuestionShowColumnPage> with AutomaticKeepAliveClientMixin{
  // 创建内置属性接受外部数据,我也不知道为什么要加final关键词，按照课程还是加上
  Question question;
  bool answerFlag;
  String countMsg;
  final int sourceType;
  List<Widget> textList = [];
  // 初始化函数
  QuestionShowColumnState({Key key, this.question, this.answerFlag, this.countMsg,this.sourceType});

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(20.0),
      child: ListView (
        shrinkWrap: true,
        children: <Widget>[
          this.getFirstRow(),
          Text("${question.main}",
            textDirection: TextDirection.ltr,
            style: new TextStyle(
              color: Colors.black, //字体颜色
              fontSize: 18.0,
              height: 1.5,
              letterSpacing: 1.0, //字体间距
              textBaseline: TextBaseline.alphabetic,
            ),
          ),
          getEmptyText(),
          _mainImages(),
          getEmptyText(),
          _optionList(),
          this.getEmptyText(),
          this._analyzing(),
          this._answerTotal(),
        ],
      ),
    );
  }
  // 选择题列表
  Widget _mainImages(){
    if(question.mainImageUrl == null){
      return Container();
    }else{
      List<String> imageUrlList = question.mainImageUrl.split(",");
      return Container(
        child: ListView.builder(
            shrinkWrap: true,
            itemCount: imageUrlList.length,
            itemBuilder: (BuildContext context,int index){
              var imageUrl = imageUrlList[index];
              return Image.network(imageUrl,
                fit: BoxFit.fitWidth,
                width: ScreenUtil().width,
              );
            }),
      );
    }
  }
  // 选择题列表
  Widget _optionList(){
    if(question.options == null || question.options.length == 0){
      return Container();
    }else{
      return Container(
        child: ListView.builder(
            shrinkWrap: true,
            itemCount: question.options.length,
            itemBuilder: (BuildContext context,int index){
              var item = question.options[index];
              return Text(StringUtils.trim(item),
                style: new TextStyle(
                  color: Colors.black, //字体颜色
                  fontSize: 18.0,
                  height: 1.5,
                  letterSpacing: 1.0, //字体间距
                  textBaseline: TextBaseline.alphabetic,
                ),
              );
            }),
      );
    }
  }
  /*
   * 空白行
   */
  Text getEmptyText(){
    return Text("",
      style: TextStyle(
        height: 0.5,
      ),
    );
  }
  Row getFirstRow(){
    return Row(
      children: <Widget>[
        getSort(),
        getCollect(),
      ],

    );

  }
  /*
   * 空白行
   */
  Text getSort(){
    String countMsg_ = this.question.typeName + " " + (this.countMsg == null? "":countMsg);
    return Text(countMsg_,
      textDirection: TextDirection.ltr,
      style: new TextStyle(
        color: Colors.blueAccent, //字体颜色
        fontSize: 20.0,
        height: 1.5,
        letterSpacing: 1.0, //字体间距
        textBaseline: TextBaseline.alphabetic,
      ),
    );
  }

  Widget getCollect(){
    return StackIndex(question, sourceType);
  }

  // 答案
  Widget _analyzing() {
    String answer = (this.question.answer == null && this.question.answerImageUrl ==null) ? "无" : (this.question.answer == null?"":this.question.answer);
    String answer_ = this.answerFlag?"解析: ":"解析: ********";
    return new Container(
        alignment: Alignment.topLeft,
        child: GestureDetector(
          child: Text(
            answer_,
            style: TextStyle(
              color: Colors.blueAccent, //字体颜色
              fontSize: 18.0,
              height: 1.5,
              letterSpacing: 1.0, //字体间距
              textBaseline: TextBaseline.alphabetic,
            ),
          ),
          onTap: (){
            setState(() {
              this.answerFlag = !this.answerFlag;
            });
          },
        )
    );
  }
  // 信息
  Widget _answerTotal(){
    if(answerFlag){
      if(question.answerImageUrl != null && question.answer != null){
        return Container(
          child: Column(
            children: <Widget>[
              _answerText(),
              _answerImages(),
            ],
          ),
        );
      }else if(question.answerImageUrl == null && question.answer != null){
        return _answerText();
      }else if(question.answerImageUrl != null && question.answer == null){
        return _answerImages();
      }
      return Container(
        child: Center(
          child: Text('暂无答案'),
        ),
      );
    }
    return Container();
  }
  // 答案文本
  Widget _answerText() {
    return  Container(
          alignment: Alignment.topLeft,
          margin: EdgeInsets.only(top: 5.0),
          child: Text(
            this.question.answer,
            style: TextStyle(
              color: Colors.green, //字体颜色
              fontSize: 17.0,
              height: 1.5,
              letterSpacing: 1.0, //字体间距
              textBaseline: TextBaseline.alphabetic,
            ),
          ),
    );
  }

  // 答案图片
  Widget _answerImages(){
    if(question.answerImageUrl == null){
      return Container();
    }else{
      List<String> imageUrlList = question.answerImageUrl.split(",");
      return Container(
        margin: EdgeInsets.only(top: 5.0),
        child: ListView.builder(
            shrinkWrap: true,
            itemCount: imageUrlList.length,
            itemBuilder: (BuildContext context,int index){
              var imageUrl = imageUrlList[index];
              return Image.network(imageUrl,
                fit: BoxFit.fitWidth,
                width: ScreenUtil().width,
              );
            }),
      );
    }
  }
  Widget isCollectText() {
    String collect = "收藏: ";
    return new Row(
        children: <Widget>[
          Text(collect,
            style: TextStyle(
              color: Colors.blueAccent, //字体颜色
              fontSize: 16.0,
              height: 1.0,
              letterSpacing: 1.0, //字体间距
              textBaseline: TextBaseline.alphabetic,
            ),
          ),
          Container(
              child:StackIndex(question, sourceType),
          )
        ],
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;


}

/*
 * 收藏
 */
class StackIndex extends StatefulWidget {
  Question question;
  int sourceType;
  StackIndex(this.question, this.sourceType) : super();
  @override
  State<StatefulWidget> createState() => new StackIndexSate(this.question, this.sourceType);
}

class StackIndexSate extends State<StackIndex> {
  Question question;
  int sourceType;
  StackIndexSate(this.question, this.sourceType) : super();

  int currIndex;
  int questionId;
  int courseId;

  @override
  void initState() {
    super.initState();
    currIndex = question.collectFlag;
    questionId = question.id;
    courseId = question.courseId;
  }

  @override
  Widget build(BuildContext context) {
    return IndexedStack(
      index: currIndex,
      children: [
        IconButton(
          icon: Icon(Icons.favorite_border,
            size: 28.0,
            color: Colors.red,
          ),
          onPressed: _onPressed,
        ),
        IconButton(
          icon: Icon(Icons.favorite,
            size: 28.0,
            color: Colors.red,
          ),
          onPressed: _onPressed,
        ),
      ],
    );
  }

  _onPressed(){
    // 调用接口逻辑
    setState(() {
      this.currIndex = this.currIndex == 0 ? 1:0;
      question.setCollectFlag(currIndex);
      this._collect();
    });
  }

  void _collect() async {
    var url = '';
    if(sourceType == 1){
      url = 'questionInfo/collect';
    }else if(sourceType == 2){
      url = 'courseQuestionInfo/collect';
    }
    String result;
    int questionFlag = this.currIndex == 1 ? 2:0;
    var formPage = {'questionId':questionId,"questionFlag":questionFlag,"courseId":courseId};
    try {
      request_post_json(url, formData:formPage).then((val){
        var response = json.decode(val.toString());
//        print("调用接口：questionFlag： $response");
      });
    } catch (exception) {}
    if (!mounted) return;
  }

}